package cn.hls.web.controller.base;

import java.io.File;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.hls.entity.vo.Msg;
import cn.hls.until.GenericsUtils;

import com.alibaba.fastjson.JSON;

/**
 * @fileName: UploadAction.java
 * @Description: 文件上传
 * @author: yinghui.zhang
 * @email: uuhui@163.com
 * @date 2015年7月7日
 * @version V1.0
 */
@SuppressWarnings("rawtypes")
@Controller
@RequestMapping("upload")
public class UploadController extends BaseController {
	/**
	 * 文件上传
	 */
	@RequestMapping("uploadFile")
	@ResponseBody
	public Msg uploadFile(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile file)throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		if (file != null) {
			try {
				String dirPath=GenericsUtils.dateFormat(new Date(), "yyyyMMdd")+"/";
				String fileServerPath = request.getSession().getServletContext().getRealPath("/") + 
				"/upload/" + GenericsUtils.dateFormat(new Date(), "yyyyMMdd");
				 String ext = FilenameUtils.getExtension(file.getOriginalFilename());
				 String oldFileName=request.getParameter("photo");
				 if(StringUtils.hasText(oldFileName)){
					String oldFilePath= request.getSession().getServletContext().getRealPath("/") + "/upload/"+oldFileName;
					 File oldFile=new File(oldFilePath);
					 if(oldFile.exists()){
						 oldFile.delete();
					 }
				 }
				String fileName = UUID.randomUUID().toString().replace("-", "")+"." + ext;
				File savefile = new File(new File(fileServerPath), fileName);
				if (!savefile.exists()) {
					savefile.mkdirs();
					// 转存文件
					file.transferTo(savefile);
				}
				msg.setInfo(dirPath+fileName);
				msg.setStatus(200);
			} catch (Exception e) {
				msg.setInfo("上传失败");
				msg.setStatus(201);
			}
		}
		response.getWriter().write(JSON.toJSONString(msg));
		return null;
	}
	@RequestMapping("delFile")
	@ResponseBody
	public Msg del(HttpServletRequest request,String fileName)throws Exception{
		if(StringUtils.hasText(fileName)){
			String filePath= request.getSession().getServletContext().getRealPath("/") + "/upload/"+fileName;
			File file=new File(filePath);
			 if(file.exists()){
				 file.delete();
				 msg.setInfo("操作成功");
				 msg.setStatus(200);
			 }else{
				msg.setInfo("文件不存在");
				msg.setStatus(201);
			 }
		}else{
			msg.setInfo("文件不存在");
			msg.setStatus(201);
		}
		return msg;
	}

}
